﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Reflection;
using X23.Util.StringUtil;

namespace X23.EFCore
{
    public class EFCoreContext : DbContext
    {
        public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });


        public EFCoreContext(DbContextOptions<EFCoreContext> options) : base(options)
        {

        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

#if DEBUG
            optionsBuilder.UseLoggerFactory(MyLoggerFactory);//输出日志
#endif
            base.OnConfiguring(optionsBuilder);

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //通过程序集注入方式 使用 fluent API 配置模型
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());

            //更改表映射 RenameSnakeCase()将大驼峰命名转为蛇形命名
            //eg. User.cs => 数据库表 user
            //    字段User.WeChatId => 数据库表 user表 字段 wx_chat_id
            foreach (var entity in modelBuilder.Model.GetEntityTypes())
            {
                modelBuilder.Entity(entity.Name, builder =>
                {
                    builder.ToTable(entity.ClrType.Name.RenameSnakeCase());
                    foreach (var property in entity.GetProperties())
                    {
                        var propertyBuilder = builder.Property(property.Name);
                        propertyBuilder.HasColumnName(property.Name.RenameSnakeCase());

                        #region 设置decimal类型精度
                        if (property.ClrType == typeof(decimal))
                        {
                            propertyBuilder.HasColumnType("decimal(18,2)");
                        }
                        #endregion
                    }
                });
            }

            //数据库迁移
            //get-help entityframeworkcore
            //Add-Migration init（执行此命令项目生成一个目录（Migration））
            //Update-Database init
            //Update-Database -Args '--environment Work'
        }
    }
}
